package com.example.moudlelibrary.tools;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.net.MalformedURLException;
/**
 * Created by HeYuanqing on 2024/06/29  16:04
 **/

public class HttpUtils {
    private static final int TIMEOUT = 5000; // 设置请求超时时间，单位毫秒

    private HttpUtils() {
        // 防止实例化
    }

    /**
     * 发送GET请求。
     *
     * @param url 请求的URL地址
     * @return 响应的内容，如果发生错误则返回null
     * @throws IllegalArgumentException 如果URL不合法或为空
     * @throws CustomHttpRequestException 如果HTTP请求过程中发生错误
     */
    public static String GET(String url) throws IllegalArgumentException, CustomHttpRequestException {
        if (url == null || url.isEmpty() || !url.matches("https?://.*")) {
            throw new IllegalArgumentException("URL is invalid or empty.");
        }

        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");
            con.setConnectTimeout(TIMEOUT);
            con.setReadTimeout(TIMEOUT);
            con.setInstanceFollowRedirects(true); // 处理重定向

            int responseCode = con.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
                    StringBuilder response = new StringBuilder(); // 预分配StringBuilder的容量
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    return response.toString();
                }
            } else {
                // 记录非200响应码的日志，以便于问题诊断
                System.out.println("GET request failed. Response Code: " + responseCode);
                return null;
            }
        } catch (MalformedURLException e) {
            throw new CustomHttpRequestException("URL is malformed.", e);
        } catch (IOException e) {
            throw new CustomHttpRequestException("IOException occurred.", e);
        } catch (Exception e) {
            throw new CustomHttpRequestException("An unexpected error occurred.", e);
        }
    }



    /**
     * 发送POST请求。
     *
     * @param url       请求的URL地址
     * @param postData  POST请求的数据，格式如"name=value&name2=value2"
     * @return 响应的内容，如果发生错误则返回null
     */
    public static String  POST(String url, String postData) {
        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setRequestProperty("Charset", "utf-8");
            con.setDoOutput(true);
            con.setConnectTimeout(TIMEOUT);
            con.setReadTimeout(TIMEOUT);

            try (OutputStream os = con.getOutputStream()) {
                byte[] input = postData.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                StringBuilder response = new StringBuilder();
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                return response.toString();
            } else {
                return null;
            }
        } catch (Exception e) {
            System.out.println("POST request error: " + e.getMessage());
            return null;
        }
    }
}
